//
//  GroupDetailsAsParticipantViewController.swift
//  puretennis
//
//  Created by IYE Technologies on 11/24/14.
//  Copyright (c) 2014 IYE Technologies. All rights reserved.
//

import UIKit

class GroupDetailsAsParticipantViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
   
    @IBOutlet weak var tableView: UITableView!;
    
    var group:NSDictionary!;
    
    var ownerGuid:String!;
    
    var groupParticipantsAmount = 1;
     /*
    *
    * Contain participants
    **/
    var dataSource:[NSDictionary] = [];
    
    override func viewDidLoad() {
        super.viewDidLoad()
        ViewUtils.addBackgroundView(self);
        self.tableView.dataSource = self;
        self.tableView.delegate = self;
        self.tableView.layer.masksToBounds = true;
        self.tableView.layer.cornerRadius = 4;
        
        self.initNavigation();
        self.loadGroupDetails();
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated);
        self.updateTitile();
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated);
        self.hideTabBar();
    }
 
    func initNavigation(){
        self.updateTitile();
        var backButton = UIButton();
        backButton.addTarget(self, action: Selector("back:"), forControlEvents: UIControlEvents.TouchUpInside);
        backButton.setImage(UIImage(named: "back"), forState: UIControlState.Normal);
        backButton.showsTouchWhenHighlighted = true;
        backButton.contentMode = UIViewContentMode.Left;
        backButton.sizeToFit();
        var backBarItem = UIBarButtonItem(customView: backButton);
        self.navigationItem.leftBarButtonItem = backBarItem;
        
        var menuButton = UIButton();
        menuButton.setImage(UIImage(named: "arrow"), forState: UIControlState.Normal);
        menuButton.addTarget(self, action: Selector("openMenu:"), forControlEvents: UIControlEvents.TouchUpInside);
        menuButton.showsTouchWhenHighlighted = true;
        menuButton.contentMode = UIViewContentMode.Left;
        menuButton.sizeToFit();
        var menuNavBarButtonItem = UIBarButtonItem(customView: menuButton);
        self.navigationItem.rightBarButtonItem = menuNavBarButtonItem;
    }
    
    func openMenu(sender:UIButton){
        var frame = self.navigationController!.navigationBar.frame;
        frame.origin.x = self.navigationItem.rightBarButtonItem!.customView!.frame.origin.x;
        frame.size.width = self.navigationItem.rightBarButtonItem!.customView!.frame.width;
        
        var chat = KxMenuItem("群聊",image: nil,target: self,action: Selector("chat:"));
        var leave = KxMenuItem("退出",image: nil,target: self,action: Selector("leaveGroup:"));
        KxMenu.setTitleFont(Utils.defaultFont());
        KxMenu.showMenuInView(self.navigationController!.view, fromRect: frame, menuItems: [chat,leave]);
    }
    
    // Chat
    func chat(menuItem:KxMenuItem){
        
    }
    
    func leaveGroup(menuItem:KxMenuItem){
        var groupGuid = group.objectForKey("guid") as String;
        var url = "/api/v1/group?groupGuid=\(groupGuid)";
        HttpUtils.sendRequest(url, method: RequestMethod.DELETE, httpBody: nil, successHandle: { (response) -> Void in
            Utils.debug("Leave group the guid [\(groupGuid)]");
            self.navigationController?.popViewControllerAnimated(true);
            }, errorHandle: { (error) -> Void in
        });
    }
    
    func initSendJoinGroupRequestButton(){
        var joinButton = UIButton();
        joinButton.addTarget(self, action: Selector("sendJoinRequest:"), forControlEvents: UIControlEvents.TouchUpInside);
        joinButton.setImage(UIImage(named: "add"), forState: UIControlState.Normal);
        joinButton.showsTouchWhenHighlighted = true;
        joinButton.contentMode = UIViewContentMode.Right;
        joinButton.sizeToFit();
        var joinBarItem = UIBarButtonItem(customView: joinButton);
        self.navigationItem.rightBarButtonItem = joinBarItem;
    }
    
    func setup(group:NSDictionary){
        self.group = group;
    }
    
    func loadGroupDetails(){
        self.processing();
        var groupGuid = group.objectForKey("guid") as String;
        var url = "/api/v1/group?groupGuid=\(groupGuid)";
        HttpUtils.sendRequest(url, method: RequestMethod.GET, httpBody: nil, successHandle: { (response) -> Void in
            var groupDetails = response as NSMutableDictionary;
            
            var inGroup = groupDetails.objectForKey("inGroup") as Bool;
            if(!inGroup){
                self.initSendJoinGroupRequestButton();
            }
            
            var groupOwner = groupDetails.objectForKey("owner") as NSMutableDictionary;
            self.ownerGuid = groupOwner.objectForKey("guid") as String;
            self.groupParticipantsAmount = groupDetails.objectForKey("participantsAmount") as Int;
            
            self.dataSource = groupDetails.objectForKey("dataSource") as [NSDictionary];
            self.tableView.reloadData();
            
            self.processComplete();
            }, errorHandle: { (error) -> Void in
            self.processComplete();
        });
        
    }
    
    func updateTitile(){
        var groupName = self.group.objectForKey("name") as String;
        self.navigationItem.titleView = ViewUtils.titleView(groupName);
    }
    
    // back action handler
    func back(barButtonItem:UIBarButtonItem){
        self.navigationController?.popViewControllerAnimated(true);
    }

    // Send join request action handler
    func sendJoinRequest(barButtonItem:UIBarButtonItem){
        self.processing();
        var groupGuid = group.objectForKey("guid") as String;
        var url = "/api/v1/group/joinrequest/request";
        var postData = NSMutableDictionary();
        postData.setObject(groupGuid, forKey: "guid");
        HttpUtils.sendRequest(url, method: RequestMethod.POST, httpBody: postData, successHandle: joinRequestSendSuccess, errorHandle: { (error) -> Void in
            self.processComplete();
        });
    }
    
    func joinRequestSendSuccess(response:AnyObject?){
        self.processComplete();
        UIAlertView(title: "发送成功", message: "发送成功", delegate: self, cancelButtonTitle: "好的").show();
        self.navigationController?.popViewControllerAnimated(true);
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count;
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var participant = self.dataSource[indexPath.row] as NSDictionary;
        var user = participant.objectForKey("user") as NSMutableDictionary;
        var cell = GroupPersionalCell.create(tableView.frame.width, user: user,ownerGuid: self.ownerGuid);
        return cell;
    }
    
    func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        var participant = self.dataSource[indexPath.row] as NSDictionary;
        var user = participant.objectForKey("user") as NSDictionary;
        var userGuid = user.objectForKey("guid") as String;
        var isCurrentUser = Utils.isCurrentUser(userGuid);
        return (isCurrentUser && self.ownerGuid != userGuid);
    }
    
    func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
        var leaveGroupAction = UITableViewRowAction(style: UITableViewRowActionStyle.Normal, title: "") { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in
            self.leaveGroup(action, indexPath: indexPath);
        }
        leaveGroupAction.backgroundColor = UIColor(patternImage: UIImage(named: "close_in_row")!);
        return [leaveGroupAction];
    }
    
    func leaveGroup(action:UITableViewRowAction!, indexPath:NSIndexPath!){
        var url = "/api/v1/group/leave";
        var participant = self.dataSource[indexPath.row] as NSDictionary;
        var user = participant.objectForKey("user") as NSDictionary;
        var userGuid = user.objectForKey("guid") as String;
        var groupGuid = group.objectForKey("groupGuid") as String;
        var postBody = NSMutableDictionary();
        postBody.setObject(groupGuid, forKey: "groupGuid");
        postBody.setObject(userGuid, forKey: "userGuid");
        HttpUtils.sendRequest(url, method: RequestMethod.POST, httpBody: postBody, successHandle: { (response) -> Void in
            self.dataSource.removeAtIndex(indexPath.row);
            self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic);
            self.groupParticipantsAmount--;
            self.initSendJoinGroupRequestButton();
            }, errorHandle: { (error) -> Void in
                
        });
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        var dictionary = self.dataSource[indexPath.row] as NSDictionary;
        var user = dictionary.objectForKey("user") as NSDictionary;
        var userGuid = user.objectForKey("guid") as String;
        var isCurrentUser = Utils.isCurrentUser(userGuid);
        if(isCurrentUser){
            var tabBarController = self.tabBarController as PureTennisTabBarController;
            tabBarController.toggleView(tabBarController.customItems.last!);
        } else {
            var userDetailsViewController = UserDetailsViewController();
            userDetailsViewController.guid = userGuid
            userDetailsViewController.loadUserDetails();
            self.navigationController!.pushViewController(userDetailsViewController, animated: true);
        }
    }
    
    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        Utils.debug("Memory warning")
    }
}
